#include <iostream>
#include <memory>
#include <boost/asio.hpp>
//#include <functional>
#include <vector>
#include <boost/date_time/posix_time/posix_time.hpp>

class printer {
public:
	printer(boost::asio::io_service &io)
	: timer_(io, boost::posix_time::seconds(1)), count_(0){
//		timer_.async_wait(std::bind(&printer::print, this));
		//bind -> function<void(const boost::system::error_code)>
		//回调函数，是成员函数，bind(指针， 使用者); 
		//注意生命周期，new出来的，或者析构
		timer_.async_wait( [this](const boost::system::error_code& error) { 
			if(error == boost::asio::error::operation_aborted)
				std::cout << "Cancel now." << std::endl;
				//此刻this已经失效了，lambda生命周期是好的，
			else
				this->print(); 
			} );
	}
	~printer() { 
		//timer_.cancel();加不加一样，deadline_timer析构也会调用，这析构晚
		std::cout << "Final count is " << count_ << std::endl; 
	}
	void print() {
		if (count_ < 5) {
			std::cout << count_ << std::endl;
			++count_;

			timer_.expires_at(timer_.expires_at() + boost::posix_time::seconds(1));
			//timer_.async_wait(std::bind(&printer::print, this));
			timer_.async_wait([this](const auto& error){ 
				if(error == boost::asio::error::operation_aborted)
					std::cout << "Cancel now\n";
				else	
					this->print(); 
				});
		}

	}
private:
	boost::asio::deadline_timer timer_;
	int count_;
};
int main() {
	boost::asio::io_service io;
	{
		printer p(io);
		//析构了，绑定的东西已经失效了
	}
	io.run();
	return 0;
}
